package com.yangjun.controller.realtimeLiveAnalysis.realtimeSituation;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.yangjun.common.DVConstants;
import com.yangjun.dao.IRealTimeOverview;
import com.yangjun.dao.mybatis.mapper.realtimeLiveAnalysis.DvDwKadLiveWareOutstockMapper;
import com.yangjun.entity.realtimeliveAnalysis.DvDwKadLiveWareOutstock;
import com.yangjun.entity.realtimeliveAnalysis.RealTimeOverviewEntity;
import com.yangjun.entity.realtimeliveAnalysis.WareOrderOutMonthDetails;
import com.yangjun.utils.DvDateUtils;
import com.yangjun.utils.EchartUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: xvitcoder
 * Date: 12/20/12
 * Time: 5:27 PM
 */
@RestController
@RequestMapping("/realtime")
public class RealTimeOverviewController {
    @Autowired
    IRealTimeOverview realTimeOverview;
    @Autowired
    private DvDwKadLiveWareOutstockMapper mapper;
    //,@RequestParam(value = "pageNum",required = true)String pageNum
    //获取物流表格数据
    @RequestMapping("/findWareOutstock")
    @ResponseBody
    public PageInfo<DvDwKadLiveWareOutstock> findDvDwKadLiveWareOutstock(HttpServletResponse response,
    		@RequestParam(value = "pageNum",required = true)String pageNum,
    		@RequestParam(value = "pageSize",required = true)String pageSize){
    	DvDwKadLiveWareOutstock dvDwKadLiveWareOutstock = new DvDwKadLiveWareOutstock();
    	PageHelper.startPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize),true,true,true);
    	PageHelper.orderBy("IMPACT_QTY asc");
    	PageInfo<DvDwKadLiveWareOutstock> page = new PageInfo<DvDwKadLiveWareOutstock>(mapper.queryList(dvDwKadLiveWareOutstock));
    	
    	return page;
    }
    
    
    @RequestMapping("/findWareOutstockDetails")
    @ResponseBody
    public Map<String, Object> findWareOutstockDetails(HttpServletResponse response,
    		@RequestParam(value = "warecode",required = true)String warecode){
    	response.setCharacterEncoding("UTF-8");
    	response.setContentType("text/html;charset=UTF-8");
//    	System.err.println("warecode-->"+warecode);
    	 List<Map<String, Object>> wareOutstockDetails = realTimeOverview.wareOutstockDetails(warecode);
    	 System.out.println("wareOutstockDetails=="+wareOutstockDetails.size());
    	 String[] legend = {"趋势图"};
		 Map<String, Object> wareOutstockDetailsMap = EchartUtils.getBrokenOneLineMap("data_date", "saleqty", legend, wareOutstockDetails);

    	return wareOutstockDetailsMap;
    	
    	
    }
 
    
    /**
     * http://192.168.7.38:8080/realtime/qsIndex
     * @param response
     * @param platformstr
     * @param today
     * @param contrastday
     * @return
     */
    @RequestMapping("/qsIndex")
    @ResponseBody
    public Map<String,Object> getIndexPage(HttpServletResponse response,
    		@RequestParam(value = "platformstr",required = false)String platformstr,
    		@RequestParam(value = "today",required = false)String today,
    		@RequestParam(value = "contrastday",required = false)String contrastday) {
	   	 Map<String,Object> resultMap = Maps.newHashMap();
	   //处理平台数组
    	String[] platformarr = new String[]{};
    	if(StringUtils.isNotBlank(platformstr)){
    		platformarr = platformstr.replace(" ","").split(",");
    	}
    	if (StringUtils.isBlank(today))
    		today = DvDateUtils.getDate(new Date(), 0);
    	if (StringUtils.isBlank(contrastday))
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	
    	String yestoday = DvDateUtils.getDate(new Date(), -1);
    	
    	List<String> ordersourceList = Arrays.asList(platformarr);
    	//获取总览表格数据
   	 	List<RealTimeOverviewEntity> realTimeOverviewEntityList = realTimeOverview.findRealTimeOverview(ordersourceList,yestoday,today,contrastday);
	   	if(realTimeOverviewEntityList!=null){
	   		if(realTimeOverviewEntityList.size()==3){
	   			RealTimeOverviewEntity one = realTimeOverviewEntityList.get(0);
	   			RealTimeOverviewEntity two = realTimeOverviewEntityList.get(1);
	   			RealTimeOverviewEntity three = realTimeOverviewEntityList.get(2);
	   			if(one!=null){
	   				if(contrastday.equals(one.getDate())){
	   					resultMap.put("contrastday",one);
	   				}else if(yestoday.equals(one.getDate())){
	   					resultMap.put("yesterday",one);
	   				}if(today.equals(one.getDate())){
	   					resultMap.put("today",one);
	   				}
	   			}
	   			if(two!=null){
	   				if(contrastday.equals(two.getDate())){
	   					resultMap.put("contrastday",two);
	   				}else if(yestoday.equals(two.getDate())){
	   					resultMap.put("yesterday",two);
	   				}if(today.equals(two.getDate())){
	   					resultMap.put("today",two);
	   				}
	   			}
	   			if(three!=null){
	   				if(contrastday.equals(three.getDate())){
	   					resultMap.put("contrastday",three);
	   				}else if(yestoday.equals(three.getDate())){
	   					resultMap.put("yesterday",three);
	   				}if(today.equals(three.getDate())){
	   					resultMap.put("today",three);
	   				}
	   			}
	   		}else if(realTimeOverviewEntityList.size()==2){
	   			RealTimeOverviewEntity one = realTimeOverviewEntityList.get(0);
	   			RealTimeOverviewEntity two = realTimeOverviewEntityList.get(1);
	   			if(one!=null){
	   				if(contrastday.equals(one.getDate())){
	   					resultMap.put("contrastday",one);
	   				} 
	   				if(yestoday.equals(one.getDate())){
	   					resultMap.put("yesterday",one);
	   				}
	   				if(today.equals(one.getDate())){
	   					resultMap.put("today",one);
	   				}
	   			}
	   			if(two!=null){
	   				if(contrastday.equals(two.getDate())){
	   					resultMap.put("contrastday",two);
	   				} 
	   				if(yestoday.equals(two.getDate())){
	   					resultMap.put("yesterday",two);
	   				}
	   				if(today.equals(two.getDate())){
	   					resultMap.put("today",two);
	   				}
	   			}
	   		}else if(realTimeOverviewEntityList.size()==1){
	   			RealTimeOverviewEntity one = realTimeOverviewEntityList.get(0);
	   			if(one!=null){
	   				if(contrastday.equals(one.getDate())){
	   					resultMap.put("contrastday",one);
	   				}else if(yestoday.equals(one.getDate())){
	   					resultMap.put("yesterday",one);
	   				}if(today.equals(one.getDate())){
	   					resultMap.put("today",one);
	   				}
	   			}
	   		}else{
	   			resultMap.put("contrastday",new RealTimeOverviewEntity());
	   			resultMap.put("yesterday",new RealTimeOverviewEntity());
	   			resultMap.put("today",new RealTimeOverviewEntity());
	   		}
	   	}else{
	   		resultMap.put("contrastday",new RealTimeOverviewEntity());
   			resultMap.put("yesterday",new RealTimeOverviewEntity());
   			resultMap.put("today",new RealTimeOverviewEntity());
	   	}
	   	//获取采购供应表格数据
	   	Map<String,Object> outstockwaresSummary = realTimeOverview.outstockwaresSummary();
		resultMap.put("sku_today", outstockwaresSummary.get(today));
		resultMap.put("sku_yesterday", outstockwaresSummary.get(yestoday));
		
    	return resultMap;
    }
    @RequestMapping(value="/selectPlatform")
    @ResponseBody
    public List<Map<String,Object>> test(HttpServletResponse response){
    	return realTimeOverview.findSelectPlatform();
    }
    
    //,method=RequestMethod.GET
    @RequestMapping(value="/chart")
    @ResponseBody
    public Map<String,Object>  showChartData(HttpServletResponse response,
    		@RequestParam(value = "today",required = false)String today,
    		@RequestParam(value = "contrastday",required = false)String contrastday,
    		@RequestParam(value = "platformstr",required = false)String platformstr){
    	//处理平台数组
    	String[] platformarr = new String[]{};
    	if(StringUtils.isNotBlank(platformstr)){
    		platformarr = platformstr.replace(" ","").split(",");
    	}
    	//要是对比日为空默认是上周
    	if(StringUtils.isBlank(contrastday)){
    		contrastday = DvDateUtils.getDate(new Date(), -7);
    	}
    	//要是今日为空默认是今天
      	if(StringUtils.isBlank(today)){
    		today = DvDateUtils.getDate(new Date(), 0);
    	}
//    	String[] indexArr = {"orderAmount","orderCnt","consignOutCnt","consignDeliverCnt","refundOrderCnt","downRefundCnt"};
    	String[] indexArr = {"orderAmount","orderCnt","refundOrderCnt","downRefundCnt"};
     	Map<String,Object> resultMap = Maps.newHashMap();
     	for(String index : indexArr){
        	resultMap.put(index, getLineChartMap(index,today,contrastday,platformarr));
     	}
     	resultMap.put("SalesAmountByPlatform",getBarChartMap("SalesAmountByPlatform",today,platformarr));
        return   resultMap;
    }
    
    /**
     * 
     * http://192.168.7.32:8080/realtime/mthchart?dateWeidu=week
     * 月度趋势
     * @param response
     * @param today
     * @param contrastday
     * @param platformstr
     * @return
     */
    @RequestMapping(value="/mthchart")
    @ResponseBody
    public Map<String,Object>  showMthchart(HttpServletResponse response,
    		@RequestParam(value = "platformstr",required = false)String platformstr,
    		@RequestParam(value = "dateWeidu",required = true)String dateWeidu){
    	
    	String curstartdate = null;
    	String curenddate = null;
    	String laststartdate = null;
    	String lastenddate = null;
    	List<String> xAxis=new ArrayList<String>();
		List<String> legendList = new ArrayList<String>();
           
    	if("week".equals(dateWeidu)){
    		curstartdate = DvDateUtils.format(DvDateUtils.getFirstDayOfWeek(new Date()),"yyyy-MM-dd");//当前周第一天
    		curenddate = DvDateUtils.format(DvDateUtils.getLastDayOfWeek(new Date()),"yyyy-MM-dd");//当前周的最后一天
    		laststartdate = DvDateUtils.format(DvDateUtils.getOffsetDay(DvDateUtils.getFirstDayOfWeek(new Date()),-7),"yyyy-MM-dd");//上周的第一天
    		lastenddate = DvDateUtils.format(DvDateUtils.getOffsetDay(DvDateUtils.getLastDayOfWeek(new Date()),-7),"yyyy-MM-dd");//上周的最后一天
    		legendList.add("上周");
    		legendList.add("本周");
    		String[] week = {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
    		xAxis = Arrays.asList(week);
    		
    	}else if("month".equals(dateWeidu)){
    		curstartdate = DvDateUtils.format(DvDateUtils.getFirstDayOfMonth(new Date()),"yyyy-MM-dd");//当月的第一天
    		curenddate = DvDateUtils.format(DvDateUtils.getLastDayOfMonth(new Date()),"yyyy-MM-dd");//当月的最后一天
    		laststartdate = DvDateUtils.format(DvDateUtils.getFirstDayOfMonth(DvDateUtils.getLastDayOfLastMonth(new Date())),"yyyy-MM-dd");//上月的第一天
    		lastenddate = DvDateUtils.format(DvDateUtils.getLastDayOfLastMonth(new Date()),"yyyy-MM-dd");//上月的最后一天
    		legendList.add("上月");
    		legendList.add("本月");
   	        String[] days = { "01","02","03","04","05","06","07","08","09","10",
	    	   "11","12","13","14","15","16","17","18","19","20",
	    	   "21","22","23","24","25","26","27","28","29","30","31"};
   	       xAxis = Arrays.asList(days);
    		
    	}else {
    		return null;
    	}
    	
    	
    	HashMap<String, Object> parameterMap = Maps.newHashMap();
    	parameterMap.put("ordersource", platformstr);
    
    	List<Integer> lastOrdercntList=new ArrayList<Integer>();//订单数 上个月
    	List<Integer> currentOrdercntList=new ArrayList<Integer>();//订单数 当前月
    	
    	List<Integer> lastNetamtList=new ArrayList<Integer>();//销售额 上个月
    	List<Integer> currentNetamtList=new ArrayList<Integer>();//销售额 当前月
    	
    	List<Integer> lastOutOrdercntList=new ArrayList<Integer>();//出库订单 上个月
    	List<Integer> currentOutOrdercntList=new ArrayList<Integer>();//出库订单 当前月
    	
    	List<Integer> lastOutpkgcntList=new ArrayList<Integer>();//出库包裹数 上个月
    	List<Integer> currentOutpkgcntList=new ArrayList<Integer>();//出库包裹数 当前月
    	
    	List<Integer> lastOutamountList=new ArrayList<Integer>();//出库金额 上个月
    	List<Integer> currentOutamountList=new ArrayList<Integer>();//出库金额 当前月
    	
    	parameterMap.put("startdate", curstartdate);
    	parameterMap.put("enddate", curenddate);
    	List<WareOrderOutMonthDetails> curWareOrderOutMonthList = mapper.wareOrderOutMonthDetails(parameterMap);
    	for (WareOrderOutMonthDetails entity : curWareOrderOutMonthList) {
    		currentOrdercntList.add(entity.getOrder_cnt());
    		currentNetamtList.add(entity.getNetamt());
    		currentOutOrdercntList.add(entity.getOut_order_cnt());
    		currentOutpkgcntList.add(entity.getOut_pkg_cnt());
    		currentOutamountList.add(entity.getOutamount());
    	}
    	
    	
    	
    	parameterMap.put("startdate", laststartdate);
    	parameterMap.put("enddate", lastenddate);
    	List<WareOrderOutMonthDetails> lastWareOrderOutMonthList = mapper.wareOrderOutMonthDetails(parameterMap);
    	for (WareOrderOutMonthDetails entity : lastWareOrderOutMonthList) {
    		lastOrdercntList.add(entity.getOrder_cnt());
			lastNetamtList.add(entity.getNetamt());
			lastOutOrdercntList.add(entity.getOut_order_cnt());
			lastOutpkgcntList.add(entity.getOut_pkg_cnt());
			lastOutamountList.add(entity.getOutamount());
    	}
    	Map<String,Object> resultMap = Maps.newHashMap();
    	Map<String,Object> orderChart = Maps.newHashMap(); 
    	orderChart.put("legend", legendList);
    	orderChart.put("xAxis", xAxis);
    	orderChart.put("cur", currentOrdercntList);
    	orderChart.put("last", lastOrdercntList);
    	resultMap.put("orderChart",orderChart);
    	
    	Map<String,Object> netamtChart = Maps.newHashMap(); 
    	netamtChart.put("legend", legendList);
    	netamtChart.put("xAxis", xAxis);
    	netamtChart.put("cur", currentNetamtList);
    	netamtChart.put("last", lastNetamtList);
    	resultMap.put("netamtChart",netamtChart);
    	
    	Map<String,Object> outOrdercntChart = Maps.newHashMap(); 
    	outOrdercntChart.put("legend", legendList);
    	outOrdercntChart.put("xAxis", xAxis);
    	outOrdercntChart.put("cur", currentOutOrdercntList);
    	outOrdercntChart.put("last", lastOutOrdercntList);
    	resultMap.put("outOrdercntChart",outOrdercntChart);
    	
    	
    	Map<String,Object> outpkgcntChart = Maps.newHashMap(); 
    	outpkgcntChart.put("legend", legendList);
    	outpkgcntChart.put("xAxis", xAxis);
    	outpkgcntChart.put("cur", currentOutpkgcntList);
    	outpkgcntChart.put("last", lastOutpkgcntList);
    	resultMap.put("outpkgcntChart",outpkgcntChart);
    	
    	
    	Map<String,Object> outamountChart = Maps.newHashMap(); 
    	outamountChart.put("legend", legendList);
    	outamountChart.put("xAxis", xAxis);
    	outamountChart.put("cur", currentOutamountList);
    	outamountChart.put("last", lastOutamountList);
    	resultMap.put("outamountChart",outamountChart);
    	
    	return   resultMap;
    }
    public Map<String, Object> getBarChartMap(String identification,String today,String[] ordersources){
    	List<String> ordersourceList = Arrays.asList(ordersources);
    	Map<String, Object> barDataMap = realTimeOverview.findSalesAmountByPlatform(today,ordersourceList);
    	barDataMap.put("name","平台销售额");
    	barDataMap.put("legend",DVConstants.REALTIME_CHART_NAME_ORDERAMOUNT);
		return barDataMap;
    }

    public Map<String,Object> getLineChartMap(String identification,String today,String contrastday,String[] ordersources){
        String[] todayHourDataArr = new String[24];
        String[] contrastdayHourDataArr = new String[24];
        List<String> ordersourceList = Arrays.asList(ordersources);
        Map<String,Object> itemMap = Maps.newHashMap();
        List<Map<String,Object>> querylist = null;
        int index = 0;
        if("orderAmount".equals(identification)){
            querylist = realTimeOverview.findOrderAmount(today,contrastday,ordersourceList);
            itemMap.put("name",DVConstants.REALTIME_CHART_NAME_ORDERAMOUNT);
        }else if("orderCnt".equals(identification)){
            querylist = realTimeOverview.findOrderCnt(today,contrastday,ordersourceList);
            itemMap.put("name",DVConstants.REALTIME_CHART_NAME_ORDERCNT);
        }else if("consignOutCnt".equals(identification)){
            querylist = realTimeOverview.findConsignOutCnt(today,contrastday,ordersourceList);
            itemMap.put("name",DVConstants.REALTIME_CHART_NAME_CONSIGNOUTCNT);
        }else if("consignDeliverCnt".equals(identification)){
            querylist = realTimeOverview.findConsignDeliverCnt(today,contrastday,ordersourceList);
            itemMap.put("name",DVConstants.REALTIME_CHART_NAME_CONSIGNDELIVERCNT);
        }else if("refundOrderCnt".equals(identification)){
            querylist = realTimeOverview.findRefundOrderCnt(today,contrastday,ordersourceList);
            itemMap.put("name",DVConstants.REALTIME_CHART_NAME_REFUNDORDERCNT);
        }else if("downRefundCnt".equals(identification)){
            querylist = realTimeOverview.findDownRefundCnt(today,contrastday,ordersourceList);
            itemMap.put("name",DVConstants.REALTIME_CHART_NAME_DOWNREFUNDCNT);
        }
        for(Map<String,Object> map : querylist){
            	String day = String.valueOf(map.get("dataDate"));
            	String hour = String.valueOf(map.get("dataHour"));
                if(hour.startsWith("0")){
                	if(day.equals(today)){
                		index = Integer.valueOf(hour);
                    	todayHourDataArr[Integer.parseInt(hour.substring(1))] =String.valueOf(map.get(identification));
                	}else{
                		contrastdayHourDataArr[Integer.parseInt(hour.substring(1))] =String.valueOf(map.get(identification));
                	}
                }else{
                	if(day.equals(today)){
                		index = Integer.valueOf(hour);
                    	todayHourDataArr[Integer.parseInt(hour)] =String.valueOf(map.get(identification));
                	}else{
                		contrastdayHourDataArr[Integer.parseInt(hour)] =String.valueOf(map.get(identification));
                	}
                }
        }
        //空的置为0
        for(int i = 0,len = contrastdayHourDataArr.length;i<len;i++){
        	if(i<index&&StringUtils.isEmpty(todayHourDataArr[i])){
        		todayHourDataArr[i] = "0";
        	}
        	if(StringUtils.isEmpty(contrastdayHourDataArr[i])){
        		contrastdayHourDataArr[i] = "0";
        	}
        }
        itemMap.put("legend",DVConstants.REALTIME_CHART_LEGEND);
        itemMap.put("xAxis", DVConstants.TWENTY_FOUR_HOURS_XAXIS);
        itemMap.put("today", todayHourDataArr);
        itemMap.put("contrastday", contrastdayHourDataArr);
        return itemMap;
    }
}
